// 学生控制器
package org.example.backend.controller;

import jakarta.validation.Valid;
import org.example.backend.dto.StudentDto;
import org.example.backend.entity.Evaluation;
import org.example.backend.entity.Internship;
import org.example.backend.entity.Student;
import org.example.backend.entity.User;
import org.example.backend.exception.BusinessException;
import org.example.backend.service.EvaluationService;
import org.example.backend.service.InternshipService;
import org.example.backend.service.StudentService;
import org.example.backend.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/student")
@CrossOrigin
@PreAuthorize("hasRole('STUDENT')")
public class StudentController {

    private static final Logger logger = LoggerFactory.getLogger(StudentController.class);

    private final StudentService studentService;
    private final UserService userService;
    private final InternshipService internshipService;
    private final EvaluationService evaluationService;
    public StudentController(StudentService studentService, UserService userService, InternshipService internshipService, EvaluationService evaluationService) {
        this.studentService = studentService;
        this.userService = userService;
        this.internshipService = internshipService;
        this.evaluationService = evaluationService;
    }

    /**
     * 学生注册（完善个人信息）
     */
    @PostMapping("/register")
    public ResponseEntity<?> registerStudent(@Valid @RequestBody StudentDto studentDto) {
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();

            // 根据用户名获取用户信息
            User user = userService.getUserByUsername(username);

            // 创建学生信息
            Student student = studentService.createStudent(studentDto, user.getId());

            Map<String, Object> response = new HashMap<>();
            response.put("message", "学生信息注册成功");
            response.put("student", student);

            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            logger.error("学生注册失败", e);
            return ResponseEntity.badRequest().body("注册失败：" + e.getMessage());
        }
    }

    /**
     * 更新学生信息
     */
    @PutMapping("/profile")
    public ResponseEntity<?> updateStudent(@Valid @RequestBody StudentDto studentDto) {
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();

            // 根据用户名获取用户信息
            User user = userService.getUserByUsername(username);

            // 获取学生信息
            Student existingStudent = studentService.getStudentByUserId(user.getId());

            // 更新学生信息
            Student student = studentService.updateStudent(existingStudent.getId(), studentDto);

            Map<String, Object> response = new HashMap<>();
            response.put("message", "学生信息更新成功");
            response.put("student", student);

            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            logger.error("更新学生信息失败", e);
            return ResponseEntity.badRequest().body("更新失败：" + e.getMessage());
        }
    }

    /**
     * 获取学生个人信息
     */
    @GetMapping("/profile")
    public ResponseEntity<?> getStudentProfile() {
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();

            // 根据用户名获取用户信息
            User user = userService.getUserByUsername(username);

            // 获取学生信息
            Student student = studentService.getStudentByUserId(user.getId());

            return ResponseEntity.ok(student);
        } catch (Exception e) {
            logger.error("获取学生信息失败", e);
            return ResponseEntity.badRequest().body("获取信息失败：" + e.getMessage());
        }
    }

    /**
     * 获取学生的最终实习成绩（包括教师和企业评定）
     */
    @GetMapping("/internships/{internshipId}/final-evaluations")
    public ResponseEntity<?> getFinalEvaluations(@PathVariable Long internshipId) {
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();

            // 根据用户名获取用户信息
            User user = userService.getUserByUsername(username);

            // 获取学生信息
            Student student = studentService.getStudentByUserId(user.getId());

            // 验证该实习是否属于当前学生
            Internship internship = internshipService.getInternshipById(internshipId);
            if (!internship.getStudentId().equals(student.getId())) {
                throw new BusinessException("无权限查看该实习的成绩信息");
            }

            // 获取该实习的评定信息
            List<Evaluation> evaluations = evaluationService.getEvaluationsByInternship(internshipId);

            // 分离教师和企业评定
            Evaluation teacherEvaluation = null;
            Evaluation companyEvaluation = null;

            for (Evaluation eval : evaluations) {
                if (eval.getEvaluatorType() == 1) { // 教师评定
                    teacherEvaluation = eval;
                } else if (eval.getEvaluatorType() == 2) { // 企业评定
                    companyEvaluation = eval;
                }
            }

            Map<String, Object> response = new HashMap<>();
            response.put("internshipId", internshipId);
            response.put("studentId", student.getId());
            response.put("teacherEvaluation", teacherEvaluation);
            response.put("companyEvaluation", companyEvaluation);

            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            logger.error("获取最终实习成绩失败", e);
            return ResponseEntity.badRequest().body("获取成绩信息失败：" + e.getMessage());
        }
    }

}
